<?php
namespace app\admin\model;

use think\Model;
use traits\model\SoftDelete;
use \app\base\DDL;
use \app\admin\model\Models;
use \app\admin\model\Syslog;

class ModelField extends Model
{
    use SoftDelete;

    protected $deleteTime = 'deltime';

    /*
        读取分页
    */
    static public function Page($pagesize,$mid=0,$kw='')
    {   
        $where=[];
        if($kw!=""){
            $where[]="(f.field_title like '%$kw%' OR f.field_name like '%$kw%')";
        }
        if($mid>0){
            $where[]="(f.mid=$mid)";
        }
        
        return self::alias('f')
        ->join("model m","f.mid=m.id")
        ->field('f.*,m.model_name')
        ->where(\implode("and",$where))
        ->order("f.orderid DESC")
        ->paginate(10, false, ['query' => request()->param()]);
    }
    /*
        保存数据
    */
    static public function SaveData($data)
    {   
        $id=$data['id']??0;
        
        unset($data['id']);
        $data['posttime']=time();
        $DDL=new DDL();
        
        $count=self::where("`mid`='".$data['mid']."' AND `field_name`='".$data['field_name']."' AND `id`<>'".$id."'")->count();
        if($count>0){
            return Result(1,'存在重复的字段名称');
        }

        $model=Models::get($data['mid']);
        $status=0;
        if($id>0){
            $status=(self::where('id',$id)->update($data))?0:1;
        }else{
            $status=(self::create($data))?0:1;
        }

        if($status==0){
            $DDL->T_Update_Field($model['model_table'],$data['field_name'],$data['data_type'],$data['data_length'],'',$data['unsigned'],'',$data['field_title']);
            if($data['field_type']=='class'){
                $DDL->T_Update_Field($model['model_table'],'parentstr','varchar',200,'','',$data['field_name'],'分类路径');
            }
            return \Result(0,'操作成功');
        }else{
            return \Result(1,'操作失败');
        }
    }
    /*
        排序
    */
    static public function Sort($data)
    {
        $ModelField=new ModelField;
        foreach($data['field_ids'] as $k=>$v){
            $list[]=['id'=>$v,'orderid'=>$data['orderid_ipt'][$k]];
        }
        return $ModelField->isUpdate()->saveAll($list);
    }
    /*
        删除字段
    */
    static function del($id)
    {
        $field=self::get($id)->toArray();
        $model=Models::get($field['mid'])->toArray();
        $DDL=new DDL();

        if(self::destroy($id)){
            $DDL->T_Drop_Field($model['model_table'],$field['field_name']);
            return true;
        }else{
            return false;
        }
    }
}